package com.triptogether.main.activities;

import java.io.IOException;

import testingActivityDeleteAfter.TripTabsTestingActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.triptogether.R;
import com.triptogether.baseclasses.BaseActivity;
import com.triptogether.baseclasses.TripTogetherDialog;
import com.triptogether.utils.androidsystem.SharedPreferencesUtils;
import com.triptogether.utils.facebook.FacebookSharedPreferences;
import com.triptogether.utils.facebook.LoginFacebookListener;
import com.triptogether.utils.gcm.GcmCons;
import com.triptogether.utils.gcm.GcmSharedPreferences;
import com.triptogether.utils.googleplayservices.GooglePlayServicesUtils;
import com.triptogether.utils.log.Logger;
import com.triptogether.utils.ws.WebServiceResult;
import com.triptogether.utils.ws.WebServiceUtils;

public class LoginActivity extends BaseActivity implements LoginFacebookListener {

	private final String TAG = Logger.makeLogTag(this.getClass());
	private TextView welcomeTextView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

	    // Always check if the Google Play Services are available for GCM...
		GooglePlayServicesUtils.checkPlayServices(this);

		// Init the views in this activity
		welcomeTextView = (TextView) findViewById(R.id.textview_welcome);

		findViewById(R.id.button_start_activity).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), TripTogetherMainActivity.class);
				startActivity(intent);
				finish();
			}
		});
		
		findViewById(R.id.button_start_testing).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),TripTabsTestingActivity.class);
				startActivity(intent);
			}
		});
	}
	
	@Override
	protected void onStart() {
	    super.onStart();
		if (SharedPreferencesUtils.getUserLogedIn(this)) {
			// Set the text on the TextView in the MainActivity
			String facebookUserNameToShow = FacebookSharedPreferences.getUserName(getApplicationContext());
			welcomeTextView.setText(getString(R.string.login_activity_welcome,
			                                  facebookUserNameToShow));
		}
		
		// Check if the user is logged in and start the main activity
//		if(SharedPreferencesUtils.getUserLogedIn(this)) {
//			Intent mainIntent = new Intent(this, TripTogetherMainActivity.class);
//			startActivity(mainIntent);
//			finish();
//		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    Session activeSession = Session.getActiveSession();
	    if(activeSession != null) {
	    	activeSession.onActivityResult(this, requestCode, resultCode, data);
	    }
	}

	/**
	 * This method run on backgroud
	 */
	private void LogInToApp() {
		new AsyncTask<Void, Void, String>() {

			protected void onPreExecute() {
				// Set the login button of facebok disabled so the user
				// won't interrupt the login procces
				findViewById(R.id.button_loginlogout).setEnabled(false);
			};
			
			@Override
			protected String doInBackground(Void... params) {
				final Context context = getApplicationContext();

				// Try to get the registration id of GCM from the
				// SharedPreferences
				String regId = GcmSharedPreferences.getRegistrationId(context);

				// Check if there is a registration id the android device
				if (regId.isEmpty()) {
					// If the registration id of GCM does not exsists, need to
					// register on GCM Servers
					GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
					try {
	                    regId = gcm.register(GcmCons.PROJECT_SENDER_ID);
                    } catch (IOException e) {
                    	Logger.LOGE(TAG, e.getMessage(), e);
                    	return getString(R.string.error_registering_on_gcm_servers);
                    }
				}

				// Get user details from Facebook to register on
				// TripTogetherServers
				String userFacebookId = FacebookSharedPreferences.getUserFacebookId(context);
				String userName = FacebookSharedPreferences.getUserName(context);

				// Store the registration id of GCM in SharedPreferences
				GcmSharedPreferences.storeRegistrationId(context, regId);

				// Register on TripTogether Servers
				WebServiceResult webServiceResult = WebServiceUtils.registerUserLogedIn(
				        userFacebookId, userName, regId);

				// If ilegal response was return
				if (webServiceResult.isStatusOK()) {

					// if nothing was wrong with the web service, the answer
					// from it, is the userId so we init the userId in SharedPreferences
					SharedPreferencesUtils.setUserId(context,
					        webServiceResult.getResponseData());

					// Indicating the user loged in to the application
					SharedPreferencesUtils.setUserLogedIn(context, true);
				} else {
					Logger.LOGE(TAG, webServiceResult.getErrorMessage());

					// Indicate the user not loged in to the application.
					// He may be connected to Facebook, but does not have to be
					// connected to the app
					SharedPreferencesUtils.setUserLogedIn(context, false);
					
					// Log out from Facebook
					Session.getActiveSession().closeAndClearTokenInformation();
					
					// If the status is failed, its means there is might be a
					// connection problem and not problem with TripTogetherServers
					if (webServiceResult.isStatusFailed()) {
						return getString(R.string.error_connection_failed_description);
					}
					
					// Return the error string to show to the user
					return getString(R.string.error_registering_on_triptogether_servers);
				}

				return "";
			}
			
			protected void onPostExecute(String result) {
				if (!result.isEmpty()) {
					TripTogetherDialog dialog = new TripTogetherDialog(
					        getString(R.string.trip_together_dialog_title_connection_problem),
					        result, getString(R.string.ok));
					dialog.show(getSupportFragmentManager(), "LoginToAppFailed");
				} else {
					// Write the welcome title for the user if the application succeeded to log in
					String facebookUserNameToShow = FacebookSharedPreferences.getUserName(getApplicationContext());
					welcomeTextView.setText(getString(R.string.login_activity_welcome,
					                                  facebookUserNameToShow));
				}

				// Set the login button of facebok enabled again
				findViewById(R.id.button_loginlogout).setEnabled(true);
			};

		}.execute(null, null);
	}
	
	/**
	 * Registers the application with GCM servers and TripTogether servers,
	 * asynchronously.</br>
	 * Stores the registration ID and the app versionCode in the application's
	 * shared preferences for future use.
	 * </br></br><b>
	 * IMPORTANT: you have to check if the userName is legal on TripTogether
	 * Servers, with: </br>
	 * WebserviceUtils.checkUserName(userName) in {@link WebserviceUtils}
	 * </b></br>
	 */
	private void LogOutFromApp() {
		new AsyncTask<Void, Void, String>() {
			
			protected void onPreExecute() {
				// Set the logout button of facebok disabled so the user
				// won't interrupt the logout process procces
				findViewById(R.id.button_loginlogout).setEnabled(false);
			};

			@Override
			protected String doInBackground(Void... params) {
				final Context context = getApplicationContext();

				// Get the userId from the SharedPreferences
				String userId = SharedPreferencesUtils.getUserId(context);

				// Register LogOut To TripTogether Servers
				WebServiceResult webServiceResult = WebServiceUtils.registerUserLogedOut(userId);

				if (webServiceResult.isStatusOK()) {
					// Set indicating the user loged out
					SharedPreferencesUtils.setUserLogedIn(context, false);
				} else {
					Logger.LOGE(TAG, webServiceResult.getErrorMessage());
					
					// Here we try to return everything back to normal, so we
					// also open the Session with facebook
//					Session.openActiveSession((LoginActivity) getApplicationContext(),
//					        true, getStatusCallback());
					
					return getString(R.string.error_registering_on_triptogether_servers);
				}

				return "";
			};
			
			protected void onPostExecute(String result) {
				if (!result.isEmpty()) {
					Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
				} else {
					// Set the login title for the user
					welcomeTextView.setText(R.string.login_activity_login_to_facebook);
				}

				// Set the logout button of facebok enabled again
				findViewById(R.id.button_loginlogout).setEnabled(true);
			};

		}.execute(null, null);
	}

	private void getDetailsFromFacebookAndLogInToApp(Session session) {
		Request.newMeRequest(session, new Request.GraphUserCallback() {
			// callback after Graph API response with user object
			@Override
			public void onCompleted(GraphUser user, Response response) {
				FacebookSharedPreferences.saveUserData(getApplicationContext(), user);
				
				LogInToApp();
			}
		}).executeAsync();
	}

	@Override
	public void onSessionOpened(Session session) {
//		boolean userLogedInFromSharedPreferences = SharedPreferencesUtils.getUserLogedIn(getApplicationContext());
//		if(!userLogedInFromSharedPreferences) {
//			getDetailsFromFacebookAndLogInToApp(session);
//		}

		Request.newMeRequest(session, new Request.GraphUserCallback() {
			// callback after Graph API response with user object
			@Override
			public void onCompleted(GraphUser user, Response response) {
				Toast.makeText(getApplicationContext(), "username is: " + user.getUsername(), Toast.LENGTH_LONG).show();
			}
		}).executeAsync();
	}
	
	@Override
	public void onSessionClosed() {
//		boolean userLogedInFromSharedPreferences = SharedPreferencesUtils.getUserLogedIn(getApplicationContext());
//		if(userLogedInFromSharedPreferences) {
//			LogOutFromApp();
//		}
		Toast.makeText(getApplicationContext(), "Logout from facebook", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onSessionClosedFailed() {
		Toast.makeText(getApplicationContext(), R.string.error_registering_on_facebook_servers, Toast.LENGTH_LONG).show();
	}
}